package com.nsi.service.Impl;

import com.aliyun.oos.demo.AliyunOSSClientUtil;
import com.aliyun.oos.demo.OSSClientConstants;
import com.aliyun.oss.OSSClient;
import com.nsi.common.Const;
import com.nsi.dao.ConfigureMapper;
import com.nsi.exception.NsiOperationException;
import com.nsi.pojo.Configure;
import com.nsi.pojo.SchoolNew;
import com.nsi.service.TemplateService;
import com.nsi.util.FileUtil;
import com.nsi.util.PropertiesUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;

@Service
@Slf4j
public class TemplateServiceImpl implements TemplateService {

    @Autowired
    private ConfigureMapper configureMapper;

    @Override
    public void uploadSchoolTemplateOOS(SchoolNew schoolNew,Configure templateString ) {
        // 本地生成文件
        String path = PropertiesUtil.getProperty("school.template.url");
        String schoolHTML = this.templateCompound(schoolNew, templateString);
        FileUtil.writeHtml(schoolNew.getId(), schoolHTML, path);

        // 山传至OOS
        File uploadFile = new File(path + schoolNew.getId() + ".html");
        this.uploadFileOos(uploadFile);
        log.info("【学校库页面上传成功！】本地文件路径:{}", uploadFile.getPath());
    }

    /**
     * 学校库内容替换
     *
     * @param schoolNew
     * @param configure
     * @return
     */
    private String templateCompound(SchoolNew schoolNew, Configure configure) {
        return configure.getTextcontent01()
                .replaceAll("ARITICLE---SCHOOLNAME", schoolNew.getSchoolName())
                .replaceAll("ARITICLE---SCHOOLENGLISHNAME", (StringUtils.isBlank(schoolNew.getSchoolEnglishName())) ? "暂无" : schoolNew.getSchoolEnglishName())
                .replaceAll("ARITICLE---TELEPHONE", (StringUtils.isBlank(schoolNew.getTelephone())) ? "暂无" : "" + schoolNew.getTelephone())
                .replaceAll("ARITICLE---SCHOOLDESC", (StringUtils.isBlank(schoolNew.getSchoolDesc())) ? "暂无" : "" + schoolNew.getSchoolDesc())
                .replaceAll("ARITICLE---WEBSITE", (StringUtils.isBlank(schoolNew.getWebsite())) ? "暂无" : "" + schoolNew.getWebsite());
    }


    private void uploadFileOos(File uploadFile) {
        OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
        AliyunOSSClientUtil.uploadObject2OSS(ossClient, uploadFile, OSSClientConstants.ARTICLE_BACKET_NAME, "data/school/");
    }


}
